<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use app\common\model\LibAdmin;
use common\Common;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Validate;

//公共函数

/**
 * 提现申请
 * @name LibAdminWithdrawalApply.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibAdminWithdrawalApply extends BaseModel
{
    protected $model;
    protected $table = 'hfztcy_admin_withdrawal_apply';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = db($this->table);
        parent::__construct();
    }

    /**
     * 添加表单信息
     */
    public function addWithdrawalApply($condition)
    {
        try {
            $condition['add_time'] = Common::getTime();
            $reslut = $this->model->insertGetId($condition);
            if (true == $reslut) {
                return Common::errorArray(0, "添加成功", $reslut);
            } else {
                return Common::errorArray(1, "添加失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }


    /**
     * 查询单个表单信息
     * @param $condition
     * @param array $result
     */
    public function findWithdrawalApply($condition = '', $field = '')
    {
        try {
            $reslut = $this->model->where($condition)->field($field)->find();

            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 查询多个表单信息
     * @param $condition
     * @param $limit
     * @param $field
     * @param $sort
     * @param array $result
     */
    public function findAllWithdrawalApply($condition = '', $limit = '', $field = '', $sort = 'add_time desc')
    {
        try {
            $reslut = $this->model->where($condition)->order($sort)->limit($limit)->field($field)->select();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 更新表单信息
     * @param $condition
     * @param $userInfo
     * @param array $result
     */
    public function updateWithdrawalApply($condition, $userInfo)
    {
        try {
            $reslut = $this->model->where($condition)->update($userInfo);
            if (true == $reslut) {
                return Common::errorArray(0, "更新成功", $reslut);
            } else {
                return Common::errorArray(1, "更新失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteWithdrawalApply($ids)
    {
        $condition = array('id' => array('in', $ids));
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值加1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function increaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setInc($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值减1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function decreaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setDec($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 分页获取数据表单信息
     */
    public function pagingWithdrawalApply($page, $whereStr)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

        $querySQL = <<< SQL
SELECT *
FROM (
    SELECT x.*,d.account,d.group_id
    FROM `{$this->table}` AS x
        LEFT JOIN `base_admin` AS d ON x.user_id = d.id
    WHERE x.user_id != 0
) AS a
WHERE {$where}
ORDER BY id DESC
SQL;

        $sql = $querySQL . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $querySQL;

        $result ['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        return $result;
    }

    /**
     * Info: 数据验证
     * Date: 2022/6/17 9:55
     */
    public function goCheck($data, $opt = 'add')
    {
        $rule = [
            'user_id' => 'require',
            'amount' => function ($value, $data) {
                $user = (new LibAdmin())->findAdmin(['user_id' => $data['user_id']]);
                if ($value == '') return '提现金额不能为空';
                if (floatval($value) == 0) return '提现金额不能为空';
                if ($value > floatval($user['data']['balance'])) return '提现金额超过用户余额';
                return true;
            },
            'audit_msg' => 'requireIf:audit_status,2',
        ];

        $msg = [
            'user_id.require' => '用户不能为空',
            'amount.require' => '提现金额不能为空',
            'audit_msg.requireIf' => '审核说明不能为空',
        ];

        $scene = [
            'add' => ['user_id', 'amount'],
            'audit' => ['user_id', 'audit_status', 'audit_msg'],
        ];

        $validate = new Validate($rule, $msg);
        $validate->scene($opt, $scene[$opt]);
        if (!$validate->scene($opt)->check($data)) {
            return Common::errorArray(1, (string)$validate->getError(), false);
        }
        return Common::errorArray(0, '验证通过', true);
    }

    /**
     * Info: 统计提现金额
     * Date: 2022/6/27 10:23
     */
    public function totalAmount($user_id)
    {
        return $this->model->where(['user_id' => $user_id, 'audit_status' => 1])->sum('amount');
    }

    /**
     * Info: 提现审核
     * Date: 2022/11/1 11:44
     */
    public function withdrawalAudit ($param)
    {
        $status = $param['status'];
        $id = $param['id'];
        $user_id = $param['user_id'];
        $amount = $param['amount'];
        $balance = $param['balance'];
        Db::startTrans();
        try {
            if ($status == 1) {
                $reason = '审核通过';
                // 扣除冻结余额
                (new LibAdmin())->decreaseField(['id' => $user_id] , 'freeze_balance',$amount);
            } else {
                $reason = input("reason");
                // 退回用户佣金
                (new LibAdmin())->increaseField(['id' => $user_id], 'balance', $amount);
                // 扣除冻结余额
                (new LibAdmin())->decreaseField(['id' => $user_id] , 'freeze_balance',$amount);
                // 余额变动记录
                $record = [];
                $record['user_id'] = $user_id;
                $record['before_balance'] = $balance;
                $record['amount'] = $amount;
                $record['is_income'] = 0;
                $record['add_time'] = Common::getTime();
                $record['info'] = '审核未通过，退回余额。原因：'.$reason;
                (new LibAdminBalanceChangeRecords())->addBalanceChangeRecords($record);
            }
            $data = [];
            $data['audit_status'] = $status;
            $data['audit_msg'] = $reason;
            $data['audit_time'] = Common::getTime();

            $this->updateWithdrawalApply(['id' => $id], $data);
            $code = 0;
            $msg = "更新成功";
            $flag = true;
            Db::commit();
        } catch (ErrorException $exception) {
            $code = 1;
            $msg = "更新失败" . $exception->getMessage();
            $flag = false;
            Db::rollback();
        }
        return Common::errorArray($code, $msg, $flag);
    }
}

?>